package com.distribute.framework.dao.impl;


import com.distribute.framework.core.web.helper.Utils;
import com.distribute.framework.core.web.util.Page;
import com.distribute.framework.core.util.Function;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Repository;
import javax.annotation.Resource;

import org.mybatis.spring.SqlSessionTemplate;

import com.distribute.framework.plugin.*;
import com.distribute.framework.dao.IInvitRecordDao;
import com.distribute.framework.model.InvitRecord;
import com.distribute.framework.model.DefineException;


/**
 * 邀请记录的Dao实现
 * @author 刘代应
 * 感谢ibatis的持久层框架 
 */
@SuppressWarnings("unchecked")
@Repository(value="invitRecordDao")
public class InvitRecordDao implements IInvitRecordDao
{
	@Resource
    private SqlSessionTemplate distributeSysSqlSessionTemplate;
	
	
	/************LAZY3Q_DEFINE_CODE************/
	/************LAZY3Q_DEFINE_CODE************/
	
	/**
	 * 自定义加工处理params,可以添加表别名、联表查询等操作
	 * 可在此动态设置数据源，以达到分库分表的目的
	 * @param params
	 * @return
	 */
	private Map custom(Map params){
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		/************LAZY3Q_DAO_CUSTOM************/
		/************LAZY3Q_DAO_CUSTOM************/
		return params;
	}
	
	/**
	 * 自定义加工处理params,可以添加表别名、联表查询等操作
	 * 可在此动态设置数据源，以达到分库分表的目的
	 * @param params
	 * @return
	 */
	private InvitRecord custom(InvitRecord params){
		
		/************LAZY3Q_CUSTOM_MODEL************/
		/************LAZY3Q_CUSTOM_MODEL************/
		return params;
	}
	
	
	
	/************LAZY3Q_DEFINE_FUNCTION************/
	/************LAZY3Q_DEFINE_FUNCTION************/
	
	/**
	 * 为某些需要加like的key加%
	 * @param params
	 * @return
	 */
	private Map filter(Map params){
		//为模糊匹配的varchar类型字段加上%号
		String[] likes={
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
		};
		for(String key:likes){
			String value=(String) params.get(key);
			if(value==null || value.trim().equals(""))
				params.remove(key);
			else
				params.put(key, "%"+value.replaceAll("%", "")+"%");
		}
		
		//如果输入的字串大于设定的长度，并且包含半角逗号的，使用in方法进行查询
		String[] ins={
		
			
			"id"			
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
			
		
		};
		for(String key:ins){
			String value=(""+params.get(key)).replace("%", "");
			if(value.indexOf(",")>-1 && value.startsWith("[") && value.endsWith("]")){
				params.put(key+"In", value.replace("'","''").replace(",", "','").replace("[", "'").replace("]", "'"));
			}
		}
		
		Object[] keys = {};
		keys = params.keySet().toArray(keys);
		for(Object key:keys){
			if(key.toString().endsWith("Not"))continue;
			Object value=params.get(key);
			if(value==null || value.toString().trim().equals(""))
				params.remove(key);
		}
		
		return params;
	}
	

	/**
	 * 获取所有邀请记录
	 * @return
	 */	
	public List<InvitRecord> getInvitRecordList(Map params,Integer offset,Integer size)
	{		
		params = custom(params);
		params.put("SIZE", size);//放入查询条数，作为缓存唯一依据
		String json = params.toString();
		String md5 = Utils.md5(json);
		
		List<InvitRecord> list = new ArrayList();
		
		
		
		if(size!=null && size!=-1)
			params.put("limit", size);
		if(offset!=null && params.get("limit")!=null)
			params.put("offset",offset);
		
	
		list = distributeSysSqlSessionTemplate.selectList("getInvitRecordList", params);
	
		
		
		
		return list;
	}
	
	
	/**
	 * 获取邀请记录统计
	 * @return
	 */
	public List getInvitRecordStats(Map params,Map<String,Object> groups,Map<String,Object> sums)
	{
		params = custom(params);
		params=filter(params);
		
		String groupSql="";
		for(Map.Entry<String, Object> item : groups.entrySet())
			if(!Utils.empty(item.getKey()))
				groupSql+=(groupSql.equals("")?"":",")+item.getValue().toString().replace("{key}",item.getKey());
		if(groups.get("definex")!=null)
			groupSql+=(groupSql.equals("")?"":",")+groups.get("definex");
		if(!groupSql.equals(""))
			groupSql = "group by "+groupSql;
		if(params.get("desc")!=null)
			groupSql+=" order by {key} desc ".replace("{key}",params.get("desc").toString());
		else if(params.get("asc")!=null)
			groupSql+=" order by {key} asc ".replace("{key}",params.get("asc").toString());
		if(!groupSql.equals(""))
			groupSql+=" limit 512 ";
			
		String selectSql="count(*) as 'count'";
		for(Map.Entry<String, Object> item : sums.entrySet())
			if(!Utils.empty(item.getKey()))
				selectSql+=(selectSql.equals("")?"":",")+item.getValue().toString().replace("{key}",item.getKey())+(item.getValue().toString().indexOf(" as ")==-1 ? (" as "+item.getKey()) : "");
		for(Map.Entry<String, Object> item : groups.entrySet())
			if(!Utils.empty(item.getKey()))
				selectSql+=(selectSql.equals("")?"":",")+item.getKey()+" as '"+item.getKey()+"'";
		if(sums.get("definex")!=null)
			selectSql+=(selectSql.equals("")?"":",")+sums.get("definex");
		
		params.put("select",selectSql);
		params.put("group",groupSql);
		return distributeSysSqlSessionTemplate.selectList("getInvitRecordStats", params);
	}

	/**
	 * 获取邀请记录分页
	 * @return
	 */
	public Page getInvitRecordPage(int page,int size,Map params)
	{
		params = custom(params);
		params=filter(params);
		
		if(size<1)size=20;
		
		//获取分页总数
		Long count= (Long) distributeSysSqlSessionTemplate.selectOne("getInvitRecordCount", params);
		//取分页的队列
		
		params.put("limit", size);
		params.put("offset", (int)Page.test(page,size,count));
		List list=distributeSysSqlSessionTemplate.selectList("getInvitRecordPage", params);
		
		//返回一个包装分页对象
		return new Page(page,size,count,list);
	}
	
	/**
	 * 获取邀请记录数量
	 * @return
	 */	
	public Long getInvitRecordCount(Map params)
	{
		params = custom(params);
		params=filter(params);
		return (Long) distributeSysSqlSessionTemplate.selectOne("getInvitRecordCount", params);
	}
	
	/**
	 * 获取邀请记录自定义求和表达式,比如求ID平均值:eval="avg(id)"
	 * @return
	 */	
	public <T> T getInvitRecordEval(String eval,Map params)
	{
		params = custom(params);
		params=filter(params); 
		params.put("eval",eval);
		Map result = (Map) distributeSysSqlSessionTemplate.selectOne("getInvitRecordEval", params);
		return result==null?null:(T)result.get("eval");
	}
	
	
	/**
	 * 根据查询条件取单个邀请记录
	 * @param params
	 * @return
	 */
	public InvitRecord getInvitRecord(Map params)
	{		
		params = custom(params);
		
		
			
		List<InvitRecord> list=this.getInvitRecordList(params,0,1);
		InvitRecord invitRecord = list.isEmpty()?null:list.get(0);
		
		
		
		
		return invitRecord;
	}
		
	/**
	 * 根据ID取邀请记录
	 * @param id
	 * @return
	 */
	public InvitRecord getInvitRecordById(Long id)
	{
		
		if(id==null)
			return null;
		
	
		InvitRecord invitRecord = null;
		if(invitRecord!=null)
			return invitRecord;
		if(invitRecord!=null && invitRecord.getId()==null)
			return null;
			
		Map params=new HashMap();
		params.put("id", id);
		params = custom(params);
		invitRecord = (InvitRecord) distributeSysSqlSessionTemplate.selectOne("getInvitRecordById",params);
		
		
		return invitRecord;
	}
	
	/**
	 * 根据ID取邀请记录(不缓存)
	 * @param id
	 * @return
	 */
	public InvitRecord GetInvitRecordById(Long id){
		Map params=new HashMap();
		params.put("id", id);
		params = custom(params);
		return  (InvitRecord) distributeSysSqlSessionTemplate.selectOne("getInvitRecordById",params);
	}
	

	/**
	 * 保存邀请记录
	 * @param invitRecord
	 */
	public InvitRecord saveInvitRecord(InvitRecord invitRecord)
	{
		invitRecord = custom(invitRecord);
		
		distributeSysSqlSessionTemplate.insert("saveInvitRecord", invitRecord);
		Long id=invitRecord.getId();
		
		
		
		
		return invitRecord;
		
	}

	

	/**
	 * 更新邀请记录
	 * @param invitRecord
	 */
	public int updateInvitRecord(InvitRecord invitRecord)
	{
		invitRecord = custom(invitRecord);
		InvitRecord dbInvitRecord = InvitRecord.get(invitRecord.getId());
		
		int rows = distributeSysSqlSessionTemplate.update("updateInvitRecord", invitRecord);
		//invitRecord = this.GetInvitRecordById(invitRecord.getId());
		
		
		
		return rows;
	}
	/**
	 * 更新邀请记录非空字段
	 * @param invitRecord
	 */
	public int updateInvitRecord$NotNull(InvitRecord invitRecord)
	{
		invitRecord = custom(invitRecord);
		InvitRecord dbInvitRecord = InvitRecord.get(invitRecord.getId());
		InvitRecord updated = invitRecord;
		
		int rows = distributeSysSqlSessionTemplate.update("updateInvitRecord$NotNull", invitRecord);
		invitRecord = this.GetInvitRecordById(invitRecord.getId());
		
		
		updated.setValues("$NotNull", true);
		
		return rows;
	}
	
	
	
	/**
	 * 根据条件更新邀请记录
	 * @param values
	 * @param params
	 */
	public int updateInvitRecordByConfirm(Map values, Map params){
	
		params = custom(params);
		
		for(Map.Entry<String,Object> entry:((Map<String,Object>)values).entrySet())
			params.put("V_"+entry.getKey(), entry.getValue());
		
		
		
		
			
		int rows = distributeSysSqlSessionTemplate.update("updateInvitRecordBy", params);
		
		
		
		return rows;
	}
	
	

	/**
	 * 根据ID删除一个邀请记录
	 * @param id
	 */
	public void deleteInvitRecordById(Long id)
	{
		Map params=new HashMap();
		params.put("id", id);
		params.put("id", id);
		params = custom(params);
		
		distributeSysSqlSessionTemplate.delete("deleteInvitRecordById", params);
		
		
		
		
	}
	
	/**
	 * 根据ID逻辑删除邀请记录 
	 * @param id
	 * @return
	 */
	public void removeInvitRecordById(Long id)
	{
		Map params=new HashMap();
		params.put("id", id);
		params.put("id", id);
		params = custom(params);
		
		distributeSysSqlSessionTemplate.update("removeInvitRecordById", params);
		
		
		
		
	}
	
	
	/**
	 * 根据条件删除邀请记录
	 * @param params
	 */
	public void deleteInvitRecordByConfirm(Map params){
	
		params = custom(params);
		
		Trigger.on(InvitRecord.class,Trigger.BEFOR,Trigger.DELETE_BY,params);
		
		
		
		
		int rows = distributeSysSqlSessionTemplate.update("deleteInvitRecordBy", params);
		
		Trigger.on(InvitRecord.class,Trigger.AFTER,Trigger.DELETE_BY,params);
	}
	
	
	/**
	 * 事务处理
	 */
	public <T> T executeTransaction(Function function) {
		return function.execute();	
	}

}